import React, { Component } from 'react';
import { Tabs, Form, Button, message } from 'antd';
import DateRangePicker from 'components/date-range-picker';
import moment from 'moment';
import ScanSendService from './scan-send.service';
import { messages } from 'share/common';
import AdvanceTable from 'components/advanced-table';
import FileSaver from 'file-saver';
import 'styles/financial-management/scan-send.scss';
import Condition from 'components/condition';
import sendPng from 'images/send-code/send.png';

const { TabPane } = Tabs;
const { SimpleTable } = AdvanceTable;
const { If, Else } = Condition;

@Form.create()
class ScanSendData extends Component {

  TableRef = null;
  state = {
    tabs: [
      {
        key: 'current-send',
        tab: messages('expense-13.key1')/*本次寄出单据*/
      }, {
        key: 'history-send',
        tab: messages('expense-13.key2')/*历史寄单*/
      }
    ],
    columns: [
      {
        title: messages('expense-13.key3')/*单据编号*/,
        dataIndex: 'businessCode'
      }, // 单据编号
      {
        title: messages('expense-13.key4')/*寄出时间*/,
        dataIndex: 'createdDate'
      } // 寄出时间
    ],
    showTable: false
  };

  handleChange = (value) => {
    this.setState({ selectedDate: value });
  };

  handleSubmit = () => {
    this.setState({ showTable: true }, () => this.TableRef.getList(true, 1));
  };

  handleCancel = () => {
    this.setState({ selectedDate: void 0 });
  };

  getPopupContainer = () => {
    return this.refs.scanData;
  };

  // 导出
  handleExport = () => {
    const searchParams = {};
    const { selectedDate } = this.state;
    selectedDate && selectedDate[0] && (searchParams.startDate = moment(selectedDate[0])
      .format('YYYY-MM-DD 00:00:00'));
    selectedDate && selectedDate[1] && (searchParams.endDate = moment(selectedDate[1])
      .format('YYYY-MM-DD 23:59:59'));
    this.setState({ confirmLoading: true });
    let hide = message.loading(messages('expense-13.key5')/*正在生成文件..*/);
    /*正在生成文件..*/
    ScanSendService.exportData({ ...searchParams })
      .then(res => {
        let b = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        let name = messages('expense-13.key6')/*已寄出单据*/;
        FileSaver.saveAs(b, `${name}.xlsx`);
      })
      .catch(() => {
        /*下载失败，请重试*/
        message.error(messages('expense-13.key7')/*下载失败，请重试*/);
      })
      .finally(() => {
        this.setState({ confirmLoading: false });
        hide();
      });
  };

  getList = (page, size) => {
    const { selectedDate } = this.state;
    let params = {};
    selectedDate && selectedDate[0] && (params.startDate = moment(selectedDate[0])
      .format('YYYY-MM-DD 00:00:00'));
    selectedDate && selectedDate[1] && (params.endDate = moment(selectedDate[1])
      .format('YYYY-MM-DD 23:59:59'));
    return ScanSendService.getData({ page, size, ...params });
  };


  renderChild = (key) => {
    const { selectedDate, columns, showTable } = this.state;
    const { sendData } = this.props;
    const domObj = {
      'history-send': (
        <section className="scan-send-history-send">
          <Form layout="inline">
            <Form.Item name="data" label={messages('expense-13.key8')/*寄单日期*/}>
              <section ref="scanData">
                <DateRangePicker
                  value={selectedDate}
                  style={{ width: '312px' }}
                  onChange={this.handleChange}
                  placeholder={messages('expense-13.key9')/*开始日期-结束日期*/}
                  getPopupContainer={this.getPopupContainer}
                />
              </section>
            </Form.Item>
            <Form.Item style={{ marginRight: 8 }}>
              <Button type="primary" htmlType="submit" onClick={this.handleSubmit}>
                {messages('common.submit')/*提交*/}
              </Button>
            </Form.Item>
            <Form.Item style={{ marginRight: 0 }}>
              <Button type="default" onClick={this.handleCancel}>
                {messages('common.clear')/*清空*/}
              </Button>
            </Form.Item>
          </Form>
          <If value={showTable}>
            <Button type="primary" htmlType="submit" className="scan-send-data-export" onClick={this.handleExport}>
              {messages('expense-13.key10')/*导出数据*/}
            </Button>
            <section className="scan-send-data-table">
              <SimpleTable
                show={['table-utils']}
                tableName="scan-send-history-table"
                onRef={ref => this.TableRef = ref}
                rowKey='businessCode'
                columns={columns}
                service={this.getList}
                notLoadWhenMount
              />
            </section>
          </If>
        </section>),
      'current-send': (
        <section className={sendData && sendData[0] ? 'scan-send-current-send-data' : 'scan-send-current-send'}>
          <Condition>
            <If value={sendData && sendData[0]}>
              {
                sendData.map(item => <span className="scan-send-current-send__span">{item}</span>)
              }
            </If>
            <Else>
              <section className="scan-send-current-send-nothing">
                <img className="scan-send-current-send__img" src={sendPng} alt="寄出"/>
                <div>{messages('expense-13.key11')/*本次还没有寄出的单据*/}</div>
              </section>
            </Else>
          </Condition>
        </section>
      )
    };
    return domObj[key];
  };

  render() {
    const { tabs } = this.state;
    return (
      <section className="scan-send-data-detail">
        <Tabs className="scan-send-data-detail">
          {tabs.map(item => React.createElement(TabPane, item, this.renderChild(item.key)))}
        </Tabs>
      </section>
    );
  }
}

ScanSendData.propTypes = {
  sendData: React.PropTypes.array
};

export default ScanSendData;
